const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const { OpenAI } = require('openai');
const fs = require('fs');
const path = require('path');

// 加载环境变量
dotenv.config();

// 初始化Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true }));

// 初始化OpenAI客户端
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

// 历史记录存储（实际应用中应使用数据库）
const drawingHistory = [];

// API路由

// 根路由
app.get('/', (req, res) => {
  res.send('AI你画我猜游戏后端API');
});

// 处理绘画猜测请求
app.post('/api/guess', async (req, res) => {
  try {
    const { image, prompt } = req.body;

    if (!image) {
      return res.status(400).json({ success: false, error: '没有提供图像数据' });
    }

    // 从Base64字符串中提取图像数据
    const base64Data = image.replace(/^data:image\/\w+;base64,/, '');
    const buffer = Buffer.from(base64Data, 'base64');

    // 保存图像到临时文件（可选）
    const tempDir = path.join(__dirname, 'temp');
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir);
    }
    const tempFileName = `temp_${Date.now()}.png`;
    const tempFilePath = path.join(tempDir, tempFileName);
    fs.writeFileSync(tempFilePath, buffer);

    // 调用OpenAI API进行图像识别
    const response = await openai.chat.completions.create({
      model: "gpt-4-vision-preview",
      messages: [
        {
          role: "user",
          content: [
            {
              type: "text",
              text: prompt || "请猜测这是什么图像"
            },
            {
              type: "image_url",
              image_url: {
                url: image
              }
            }
          ]
        }
      ],
      max_tokens: 300
    });

    // 解析OpenAI响应
    const guess = response.choices[0].message.content;

    // 保存到历史记录
    const historyItem = {
      id: drawingHistory.length + 1,
      image: image,
      guess: guess,
      timestamp: new Date().toISOString()
    };
    drawingHistory.push(historyItem);

    // 删除临时文件
    fs.unlinkSync(tempFilePath);

    // 返回结果
    res.json({
      success: true,
      guess: guess,
      confidence: 0.9, // 模拟置信度
      historyId: historyItem.id
    });
  } catch (error) {
    console.error('处理猜测请求时出错:', error);
    res.status(500).json({
      success: false,
      error: '处理请求时出错: ' + error.message
    });
  }
});

// 获取历史记录
app.get('/api/history', (req, res) => {
  res.json({
    success: true,
    history: drawingHistory
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

module.exports = app;